package com.common.util;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelUtils {

    private final static String EXCEL_2003L = ".xls";    //2003- 版本的excel
    private final static String EXCEL_2007U = ".xlsx";

    public static List<Map<String,Object>> getDataFromExcel(InputStream in, String fileName,String[] columnNames) throws Exception {
        List<Map<String,Object>> list = null;
        //创建Excel工作薄
        Workbook work = getWorkbook(in, fileName);
        if (null == work) {
            throw new Exception("创建Excel工作薄为空！");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;

        list = new ArrayList<>();
        //遍历Excel中所有的sheet
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if (sheet == null) {
                continue;
            }
            //遍历当前sheet中的所有行
            for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
                row = sheet.getRow(j);
                if (row == null || j == 0) {
                    continue;
                }

                //遍历所有的列
                Map map = new HashMap();
                for (int k = 0; k < columnNames.length; k++) {
                    Object value = getCellValue(row.getCell(k));
                    map.put(columnNames[k],value);
                }
                list.add(map);
            }
        }
        work.close();
        return list;
    }


    /**
     * 描述：根据文件后缀，自适应上传文件的版本
     *
     * @param inStr,fileName
     * @return
     * @throws Exception
     */
    public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (EXCEL_2003L.equals(fileType)) {
            wb = new HSSFWorkbook(inStr);  //2003-
        } else if (EXCEL_2007U.equals(fileType)) {
            wb = new XSSFWorkbook(inStr);  //2007+
        } else {
            throw new Exception("解析的文件格式有误！");
        }
        return wb;
    }


//    public static void main(String[] args) throws Exception {
//        String[] colums = {"c1","c2","c3","c4","c5","c6","c7","c8","c9"};
//        //InputStream in = new FileInputStream(new File("E:\\sun\\SVN\\ostms\\需求确认书\\基础功能\\导入位置信息-模板.xls"));
//        //创建HSSFWorkbook
//
//        //excel文件名
//        String fileName = "学生信息表"+System.currentTimeMillis()+".xls";
//        //sheet名
//        String sheetName = "学生信息表";
//        //HSSFWorkbook wb = ExcelUtils.getHSSFWorkbook(sheetName, colums,value , null);
//        System.out.println(1);
//    }









    /**
     * 描述：对表格中数值进行格式化
     * @param cell
     * @return
     */
    public static Object getCellValue(Cell cell){
        Object value = null;
        if(cell == null){
            return value;
        }
        DecimalFormat df = new DecimalFormat("0");  //格式化number String字符
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");  //日期格式化
        DecimalFormat df2 = new DecimalFormat("0.00");  //格式化数字
//      格式化时间
        SimpleDateFormat tdf = new SimpleDateFormat("HH:mm:ss");

        switch (cell.getCellTypeEnum()) {
            case _NONE:
                break;
            case NUMERIC:
                if("General".equals(cell.getCellStyle().getDataFormatString())){
                    value = df.format(cell.getNumericCellValue());
                }else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){
                    value = sdf.format(cell.getDateCellValue());
                }else if("h:mm".equals(cell.getCellStyle().getDataFormatString())){
                    value = tdf.format(cell.getDateCellValue());
                }else{
                    value = df2.format(cell.getNumericCellValue());
                }
                break;
            case STRING:
                value = cell.getRichStringCellValue().getString().trim();
                break;
            case FORMULA:
                break;
            case BLANK:
                value = "";
                break;
            case BOOLEAN:
                value = cell.getBooleanCellValue();
                break;
            case ERROR:
                break;
            default:
                break;
        }
        return value;
    }

    public static void setWidthAndHeight(HSSFSheet hssfSheet){
        for (int columnNum = 0; columnNum <= 21; columnNum++) {
            int columnWidth = hssfSheet.getColumnWidth(columnNum) / 256;
            for (int rowNum = 0; rowNum < hssfSheet.getLastRowNum(); rowNum++) {
                HSSFRow currentRow;
                //当前行未被使用过
                if (hssfSheet.getRow(rowNum) == null) {
                    currentRow = hssfSheet.createRow(rowNum);
                } else {
                    currentRow = hssfSheet.getRow(rowNum);
                }
                if (currentRow.getCell(columnNum) != null) {
                    HSSFCell currentCell = currentRow.getCell(columnNum);
                    if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                        int length = currentCell.getStringCellValue().getBytes().length;
                        if (columnWidth < length) {
                            columnWidth = length;
                        }
                    }
                }
            }
            hssfSheet.setColumnWidth(columnNum, columnWidth * 256);
        }
    }

}
